package org.openzip.jarsfx.unpacking.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FolderToFolderCopier {
	private String _rootPathFrom = "";
	private String _rootPathTo = "";
	
	public FolderToFolderCopier() {
		//	
	}
	
	public boolean copy(File dirFrom, File dirTo) {
		if(!dirFrom.isDirectory() || !dirFrom.canRead()) {
			return false;
		}
		
		if(!dirTo.isDirectory() || !dirTo.canWrite()) {
			return false;
		}
		
		this._rootPathFrom = dirFrom.getAbsolutePath();
		this._rootPathTo = dirTo.getAbsolutePath();
		
		this._recurse(dirFrom);
		
		return true;
	}
	
	private void _recurse(File f) {
		//projdem vsechny soubory v tomto adresari
		File[] files = f.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(files[i].isDirectory()) {
				this._recurse(files[i]);
			}
			else {
				System.out.println(files[i].getAbsolutePath());
				
				this._calcThenCopy(files[i]);
			}
		}
	}
	
	//vypocita novou cestu souboru a pak ho tam nakopiruje
	private void _calcThenCopy(File sourceFile) {
		String cleanPath = (sourceFile.getAbsolutePath()).substring(this._rootPathFrom.length());
		//System.out.println("Clean path: " + cleanPath);
		
		String newPath = this._rootPathTo + cleanPath;
		System.out.println("New path: " + newPath);
		
		
		this._copyfile(sourceFile.getAbsolutePath(), newPath);
	}
	
	private void _copyfile(String srFile, String dtFile){
		    try{
		      File f1 = new File(srFile);
		      File f2 = new File(dtFile);
		      
		      System.out.println("Parent: " + f2.getParentFile().getAbsolutePath());
		      f2.getParentFile().mkdirs();

		      InputStream in = new FileInputStream(f1);
		      
		      //For Append the file.
//		      OutputStream out = new FileOutputStream(f2,true);

		      //For Overwrite the file.
		      OutputStream out = new FileOutputStream(f2);

		      byte[] buf = new byte[1024];
		      int len;
		      while ((len = in.read(buf)) > 0){
		        out.write(buf, 0, len);
		      }
		      in.close();
		      out.close();
		      System.out.println("File copied.");
		    }
		    catch(FileNotFoundException ex){
		      System.out.println(ex.getMessage() + " in the specified directory.");
		      System.exit(0);
		    }
		    catch(IOException e){
		      System.out.println(e.getMessage());      
		    }
		  }
}
